<?php
/**
 * @copyright  Copyright  LexisNexis, a division of Reed Elsevier Inc. All rights reserved.
 */
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Elasticsearch\ClientBuilder;
use Elasticsearch\Client;

class AnalysisCommand extends Command {
    /**
     * 控制台命令名称
     *
     * @var string
     */
    protected $signature = 'queue:analysis {--script=?}';

    /**
     * 控制台命令描述
     *
     * @var string
     */
    protected $description = 'Analyse user logs';
    /**
     * @var Client
     */
    private $esClient;


    public function __construct() {
        parent::__construct();
    }

    /**
     * 执行控制台命令
     *
     * @return mixed
     */
    public function handle() {
        $esHost = [
            'host' => env('ES_HOST'),
            'port' => env('ES_PORT'),
            'user' => env('ES_USER'),
            'pass' => env('ES_PASS')
        ];
        $this->esClient = ClientBuilder::create()->setHosts([$esHost])->build();

        $scriptOption = $this->option('script');
        $nameList = [
            'Hello'
        ];

        $prefix = 'App\\Console\\Commands\\AnalysisScripts\\';
        $subfix = 'Script';
        if ($scriptOption != '?') {
            if (!in_array($scriptOption, $nameList)) {
                $this->error("Analyse Script does not exist!\n" . print_r($nameList, true));
                exit(-1);
            }
            $nameList = [$scriptOption];
        }

        $scriptList = array_map(function ($row) use ($prefix, $subfix) {
            return $prefix . $row . $subfix;
        }, $nameList);
        foreach ($scriptList as $script) {
            $this->info($script . ' starting...');
            $object = new $script($this->esClient);
            $object->analyse();
            $this->info($script . ' finished!');
        }
    }
}